package com.xbx.zuul.filter;

import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xbx.baseweb.model.User;
import com.xbx.common.constant.GlobalConstant;
import com.xbx.common.utils.DESEncryptUtils;
import com.xbx.zuul.auth.config.ShiroCleanBean;
import com.xbx.zuul.utils.UserUtlis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;

/**
 * 转发路由过滤器
 *
 * @author 89005691
 * @create 2018-10-08 11:02
 */
@Slf4j
public class AccessFilter extends ZuulFilter {

    @Value("${userInfoDesKey}")
    private String userInfoDesKey;

    @Autowired
    private ShiroCleanBean shiroCleanBean;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();

        if("OPTIONS".equalsIgnoreCase(request.getMethod())){

            log.info("OPTIONS请求通行{}", request.getRequestURI());
            return false;
        }
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();

        log.info("请求路径：" + ctx.getRequest().getRequestURI());

        // 获取用户信息
        User user = UserUtlis.getLoginUserInfo();

        if (user == null) {

            log.info("获取不到用户信息");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);

            return null;
        }

        shiroCleanBean.updatePermission(null);

        try {

            String encryptUser = DESEncryptUtils.encrypt(new Gson().toJson(user), userInfoDesKey);

            ctx.addZuulRequestHeader(GlobalConstant.GLOBAL_USER_INFO, encryptUser);
        } catch (Exception e) {

            log.error("转发路由过滤器出错", e);
        }

        return null;
    }
}
